package com.swu.education.service;

import com.swu.education.entity.CourseConnUser;
import com.swu.education.repository.CourseConnUserRepository;
import com.swu.education.util.ExcelReader;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.swu.education.entity.User;
import com.swu.education.repository.UserRepository;

import java.util.List;
import java.util.Map;

/**
 * Created by nana on 2018/3/12.
 */
@Service
public class ReadExcelFileService {

  @Autowired
  UserRepository userRepository;

  @Autowired
  CourseConnUserRepository courseConnUserRepository;

  public void importStudent(int courseId,MultipartFile file) {
    //获取到Excel中的内容
      List<Map<String, String>> list = ExcelReader.readFromExcel(file);
      //遍历list中的信息
      for (int i = 0; i < list.size(); i++) {
        Map<String, String> map = list.get(i);
        //获取EXCEL表的每一行信息
        String studentNumber = map.get("学号");
        String studentEmail = map.get("邮箱");
        String studentName = map.get("姓名");
        String groupId = map.get("组号");
        try {
          User user = userRepository.findByStudentNumber(studentNumber);
          CourseConnUser courseConnUser = new CourseConnUser();
          courseConnUser.setUserId(user.getId());
          courseConnUser.setCourseId(courseId);
          courseConnUserRepository.save(courseConnUser);
        }catch (Exception e){
          User user = new User();
          user.setStudentNumber(studentNumber);
          user.setEmail(studentEmail);
          user.setRealname(studentName);
          user.setPassword("123456");
          user.setGroupId(Integer.parseInt(groupId));
          int theNum = (int) (Math.random() * 3 + 1);
          user.setTheNumber(theNum);
          user.setRole("student");
          user = userRepository.save(user);
          CourseConnUser courseConnUser = new CourseConnUser();
          courseConnUser.setCourseId(courseId);
          courseConnUser.setUserId(user.getId());
          courseConnUserRepository.save(courseConnUser);
        }
      }
  }

}
